﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Globalization;
using SharpFileZillaStats.Properties;


namespace SharpFileZillaStats {
    public partial class MainWindow : Form {
        SharpFileZillaStats.StatsReader SR;
        Regex recentLoginFilter = new Regex(".*");
        Regex recentFileFilter = new Regex(".*");
        Regex recentIPFilter = new Regex(".*");

        private bool suspendListBoxEvents = false;
        private bool suspendTextBoxEvents = false;
       
        public MainWindow() {
            InitializeComponent();
            SR = new StatsReader();
            this.downloadChart.SR = SR;
            this.downloadMap.SR = SR;
            SR.PropertyChanged += new PropertyChangedEventHandler(SR_PropertyChanged);
          
            #if DEBUG
                SR.readFile(new System.IO.FileInfo(@"Y:\FTPServerStats\LogFiles\120227_Log_FTP-Server.log"));
            #endif
            
         
        }

        void SR_PropertyChanged(object sender, PropertyChangedEventArgs e) {
            if(e.PropertyName == "Files") {
                this.suspendListBoxEvents = true;
                this.FilterFileLb.DataSource = SR.Files.ToList();
                this.FilterIPLb.DataSource = SR.IPs.ToList();
                this.FilterLoginLb.DataSource = SR.LoginRoles.ToList();
                
                FilterLoginLb.ClearSelected();
                FilterFileLb.ClearSelected();
                FilterIPLb.ClearSelected();
                this.suspendListBoxEvents = false;
            }
            DGV.DataSource = SR.DataView;

            
        }

        private void tsbtAddLogFile_Click(object sender, EventArgs e) {
            OpenFileDialog OFD = new OpenFileDialog();
            OFD.CheckFileExists = true;
            OFD.CheckPathExists = true;
            OFD.Multiselect = true;
            OFD.InitialDirectory =  SharpFileZillaStats.Settings.Default.LogFileDirectory;
            OFD.Filter="(*.log)|*.log";
            if(OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

                SR.readFiles(OFD.FileNames);
                this.Cursor = System.Windows.Forms.Cursors.Default;
            }
        }

        private void FilterIPlb_SelectedValueChanged(object sender, EventArgs e) {
            this.setFilterRegex((ListBox)sender, ref this.recentIPFilter); 
        }

        private void FilterFilelb_SelectedValueChanged(object sender, EventArgs e) {
            this.setFilterRegex((ListBox)sender, ref this.recentFileFilter); 
        }

        private void FilterLoginlb_SelectedValueChanged(object sender, EventArgs e) {
            this.setFilterRegex((ListBox)sender, ref this.recentLoginFilter); 
        }

        private void setFilterRegex(ListBox listBox, ref Regex filterRegex) {
            if(!this.suspendListBoxEvents) {
                if(listBox.SelectedItems.Count > 0) {
                    List<String> items = new List<string>();
                    foreach(Object item in listBox.SelectedItems){
                        items.Add(item.ToString());
                    }
                    String s = "("+TextTools.combine(items, "|")+")";
                    s = s.Replace(".", "\\.");
                    filterRegex = new Regex(s);
                } else {
                    filterRegex = new Regex(".*");
                }
                this.setFilters();
            }
        }

        private void setFilters() {
            SR.setFilters(this.recentIPFilter, this.recentFileFilter, this.recentLoginFilter);
        }



        private bool isValidRegex(String s, out Regex regex) {
            bool isValid = true;
            regex = new Regex(".*");
            try {
                s = s.Trim();
                if(s.Length == 0) s = ".*";

                regex = new Regex(Regex.Replace(s,"\\\\","\\"));
            } catch {
                isValid = false;
            }
            return isValid;
        }

        private void FilterFilebtClear_Click(object sender, EventArgs e) {
            clearFilter(FilterFileLb, FilterFileTbRegex, ref this.recentFileFilter);
        }

        private void FilterIPbtClear_Click(object sender, EventArgs e) {
            clearFilter(FilterIPLb, FilterIPTbRegex, ref this.recentIPFilter);
        }

        private void FilterLoginBtClear_Click(object sender, EventArgs e) {
            clearFilter(FilterLoginLb , FilterLoginTbRegex, ref this.recentLoginFilter);
        }

        private void clearFilter(ListBox lb, TextBox tb, ref Regex regex) {
            this.suspendTextBoxEvents = true;
            this.suspendListBoxEvents = true;
            tb.Clear();
            lb.ClearSelected();
            regex = new Regex(".*");
            this.suspendTextBoxEvents = false;
            this.suspendListBoxEvents = false;
            this.setFilters();
        }

      
        private void setRegexToListBox(TextBox tb, ListBox lb) {
            String s = tb.Text.Trim();
            Regex regex;
            if(this.isValidRegex(s, out regex)) {
                EP.SetError(tb, null);
                bool isEmpty = String.IsNullOrWhiteSpace(s);
                for(int i= 0; i < lb.Items.Count; i++) {
                    String itemText = lb.Items[i].ToString();
                    this.suspendListBoxEvents = i < lb.Items.Count-1;
                    lb.SetSelected(i, !isEmpty && regex.IsMatch(itemText));
                }
            } else {
                EP.SetError(tb, String.Format("\"{0}\" is not a valid regular expression.", tb.Text));
            }
        }



        private void FilterIPBtApply_Click(object sender, EventArgs e) {
            setRegexToListBox(FilterIPTbRegex, FilterIPLb);
        }

        private void FilterFileBtApply_Click(object sender, EventArgs e) {
            setRegexToListBox(FilterFileTbRegex, FilterFileLb);
        }

        private void FilterLoginBtApply_Click(object sender, EventArgs e) {
            setRegexToListBox(FilterLoginTbRegex, FilterLoginLb);
        }

        private void tabControl_Enter(object sender, EventArgs e) {
            this.downloadChart.drawDiagram();
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e) {
            if(tabControl.SelectedTab == tabPageDiagram) {
                downloadChart.drawDiagram();
            }
            if(tabControl.SelectedTab == tabPageMap) {
                downloadMap.drawMap();
            }

        }


       

       


        

     

      
     
    }
}
